package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.dao.CategoryDao;
import com.itheima.reggie.dao.DishDao;
import com.itheima.reggie.dao.SetmealDao;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.exception.CustomerException;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired(required = false)
    private CategoryDao categoryDao;

    @Autowired(required = false)
    private DishDao dishDao;

    @Autowired(required = false)
    private SetmealDao setmealDao;

    @Override
    public void save(Category category) {
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        categoryDao.save(category);
    }

    @Override
    public Page<Category> findByPage(Integer page, Integer pageSize) {
        // 1.得到PageInfo对象
        // 设置当前页与页面大小
        PageHelper.startPage(page,pageSize);
        // 查询页面的数据
        List<Category> categoryList = categoryDao.findAll();
        // 把list传递给PageInfo对象
        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);
        // 2.把PageInfo对象的信息封装到Page对象中
        Page<Category> categoryPage = new Page<>();
        categoryPage.setRecords(pageInfo.getList());
        categoryPage.setTotal(pageInfo.getTotal());
        categoryPage.setPageSize(pageInfo.getPageSize());
        categoryPage.setPage(pageInfo.getPageNum());
        return categoryPage;
    }

    @Override
    public void deleteById(Long id) {
        // 1.查询该类别是否关联了菜品
        Integer count = dishDao.findCountByCategoryId(id);
        if (count>0){
            throw  new CustomerException("该类别已经关联菜品，不能删除！");
        }
        count = setmealDao.findCountByCategoryId(id);
        if (count>0){
            throw  new CustomerException("该类别已经关联套餐，不能删除！");
        }
        // 2.查询该类别是否关联了套餐
        categoryDao.deleteById(id);
    }

    @Override
    public void update(Category category) {
        // 修改时间
        category.setUpdateTime(LocalDateTime.now());

        categoryDao.update(category);
    }

    // 查询所有的类别信息
    @Override
    public List<Category> findAll() {
        return categoryDao.findAll();
    }

    @Override
    public List<Category> list(Integer type) {
        return categoryDao.list(type);
    }
}
